import vim
import vim_sys
import vim_server
show_info_window_name="cmd_history"

class OsInfo():
    def __init__(self):
        self.cmd_history_path=str( vim_sys.cmd_result_path("cmd_history",suffix='.cmd_history') )
        self.cmd_result_path=str( vim_sys.cmd_result_path("cmd_result",suffix=".cmd_result") )
        self.cmd_history_window=None
        self.cmd_result_window=None
        self.cmd_history_buffer=None
        self.cmd_result_buffer=None

    def history_window(self):
        if self.cmd_history_window == None \
        or self.cmd_history_window not in vim.windows \
        or  self.cmd_history_window.buffer != self.cmd_history_buffer:
            self.cmd_history_window=self.find_window(self.cmd_history_path)
            self.cmd_history_buffer=self.cmd_history_window.buffer
        return self.cmd_history_window

    def result_window(self):
        if self.cmd_result_window == None \
        or self.cmd_result_window not in vim.windows \
        or self.cmd_result_window.buffer != self.cmd_result_buffer:
            self.cmd_result_window=self.find_window(self.cmd_result_path)
            self.cmd_result_buffer=self.cmd_result_window.buffer
        return self.cmd_result_window

    def find_window(self,buffer_path):
        vim.command(f'new {buffer_path}')
        for window in vim.windows:
            if window.buffer.name == buffer_path:
                info_window=window
                break
        return info_window

osInfo=OsInfo()

def execute_os_cmd(cmd):
    cmd_info=vim_sys.execute_os_cmd(cmd)
    result=cmd
    if cmd_info['returncode'] == 0:
        result += "-- execute ok"
    else :
        result += "-- execute failure"
    print(result)

def show_os_cmd_result():
    cmd=vim.current.line.partition('.')
    print(cmd)
    vim.current.window=osInfo.result_window()
    result_buffer=vim.current.buffer
    result_buffer[:]=[]
    if len(cmd)==3 and cmd[2] in vim_sys.cmd_history:
        result_buffer.append('command:')
        result_buffer.append(cmd[2])
        result_buffer.append("-"*30)
        path=vim_sys.cmd_result_path(vim_sys.cmd_history[cmd[2]]['std_out'])
        with open(path,'r') as f:
            result_buffer.append(f.readlines())
        vim.command(":w")
        print(path)

def show_os_cmd_history():
    result=[]
    vim.current.window=osInfo.history_window()
    history_buffer=vim.current.buffer
    i=0
    for key in sorted(vim_sys.cmd_history,key=lambda key:vim_sys.cmd_history[key]["start_time"],reverse=True):
        i+=1
        exec_result="ok"
        if vim_sys.cmd_history[key]['returncode'] != 0:
            exec_result="failure"
        result.append(f"{i}.{key}")
        result.append(f'\t{exec_result}')
    history_buffer[:]=result
    vim.command(':w')
    history_buffer.options["filetype"]= show_info_window_name

    #  info_buffer.options.modifiable=0

def open_file_in_tabpage(path):
    path=fnamemodify(expand(path),':p').decode()
    for tab in vim.tabpages:
        finded=True
        for window in tab.windows:
            #  print(window.buffer.name)
            if window.buffer.name == path:
                vim.current.tabpage=tab
                vim.current.window=window
                break
        else:
            finded=False
        if finded:
            break
    else:
        #  print(f'path:{path}')
        command(f':tabnew {path}')


if __name__ == "__main__":
    #  execute('ls')
    pass
